package com.laomuji.android.mvvm.http.interceptor

import com.laomuji.android.mvvm.http.common.CommonUtil
import okhttp3.Request
import okhttp3.Response

/**
 * 日志拦截
 * @author laomuji666
 * @since 2024/2/20
 */
class LogInterceptor(private val tag: String) {
    private lateinit var _url: String

    @Synchronized
    fun requestLog(request: Request) {
        _url = request.url().toString()
        CommonUtil.log(tag, "请求开始:$_url")
        CommonUtil.log(tag, "请求方式:${request.method()}")
        CommonUtil.log(tag, "请求头:${request.headers()}")
        val body = request.body()
        if (body != null) {
            CommonUtil.log(tag, "请求体:${CommonUtil.getBodyString(body)}")
        } else {
            CommonUtil.log(tag, "请求体:null")
        }
        CommonUtil.log(tag, "请求结束:$_url")
    }

    @Synchronized
    fun responseLog(response: Response) {
        CommonUtil.log(tag, "响应开始:$_url")
        CommonUtil.log(tag, "响应码:${response.code()}")
        CommonUtil.log(tag, "响应头:\n${response.headers()}")
        try {
            CommonUtil.log(tag, "响应内容:\n${response.peekBody(Long.MAX_VALUE).string()}")
        } catch (e: Exception) {
            CommonUtil.log(tag, "响应内容:解析失败")
            e.printStackTrace()
        }
        CommonUtil.log(tag, "响应结束:$_url")
    }
}